from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
import re
import csv

# 设置 ChromeDriver 的路径
# 创建 Chrome 浏览器的服务对象
# 初始化 WebDriver
driver = webdriver.Chrome()
listdata = []

def getcardsnav():
     # # 在 b-recommended__wrapper 内查找所有 b-profile-info-card m-friend-recommended 的元素
    recommended_elements = wrapper_element.find_elements(By.CLASS_NAME, "b-profile-info-card.m-friend-recommended")

    # 遍历每个推荐的卡片
    for index, element in enumerate(recommended_elements, start=1):
        # 在每个推荐卡片内查找所有的 a 标签
        a_tags = element.find_elements(By.TAG_NAME, "a")
        
        # 打印每个 a 标签的 href 属性
        for a_index, a_tag in enumerate(a_tags, start=1):
            href = a_tag.get_attribute("href")
            pattern = r"https:\/\/onlyfans\.com\/([^\/]+)"
            match = re.search(pattern, href)
            username = match.group(1)
            
            listdata.append({"username": username, "link": href})
            
            print(f"推荐卡片 {index} 的用户名: {username}, 链接 {a_index}: {href}")

try:
    # 打开目标网页
    driver.get("https://onlyfans.com/")  # 替换为你的目标网址
    driver.maximize_window()

    # 创建 WebDriverWait 对象，最多等待10秒
    wait = WebDriverWait(driver, 10)
    
    time.sleep(5)

    # ----------------------------------------------------------------
        
        # 找到输入框
        # 输入账号密码
    
    # ----------------------------------------------------------------
    # 等待元素出现
    input_elements = driver.find_elements(By.TAG_NAME, "input")

    print(f"找到 {len(input_elements)} 个输入框。")
    print(input_elements)

    # 初始化键盘模拟工具
    actions = ActionChains(driver)

    for index, input_elem in enumerate(input_elements, start=1):
        input_type = input_elem.get_attribute("type")
        input_name = input_elem.get_attribute("name")
        input_id = input_elem.get_attribute("id")
        input_placeholder = input_elem.get_attribute("placeholder")

        print(f"输入框 {index}:")
        print(f"  类型: {input_type}")
        print(f"  名称: {input_name}")
        print(f"  ID: {input_id}")
        print(f"  Placeholder: {input_placeholder}")
        print("-" * 30)

        if index == 1:
            # 第一个输入框，假设为邮箱输入框
            try:
                input_elem.click()  # 点击输入框
                email_address = "2947151276@qq.com"  # 替换为你要输入的邮箱地址

                # 模拟键盘逐字输入
                actions.send_keys(email_address).perform()
                print(f"已在输入框 {index} 中输入邮箱: {email_address}")
            except Exception as e:
                print(f"在输入框 {index} 中输入邮箱时出错: {e}")

        elif index == 2:
            # 第二个输入框，假设为密码输入框
            try:
                input_elem.click()  # 点击输入框
                password = "Hcy08042."  # 替换为你要输入的密码

                # 模拟键盘逐字输入
                actions.send_keys(password).perform()
                print(f"已在输入框 {index} 中输入密码: {password}")
            except Exception as e:
                print(f"在输入框 {index} 中输入密码时出错: {e}")
    time.sleep(3)
    
    # ----------------------------------------------------------------
        
        # 点击提交按钮
        # 找到提交按钮并模拟点击
    
    # ----------------------------------------------------------------
    
    button_elements = driver.find_elements(By.TAG_NAME, "button")

    # print(f"找到 {len(button_elements)} 个按钮元素。")
    for index, button_elem in enumerate(button_elements, start=1):        # 获取按钮的常见属性
        if index == 4:
            button_elem.click()
            break
        
    time.sleep(50)




    # 查找 b-recommended__wrapper 的元素
    wrapper_element = driver.find_element(By.CLASS_NAME, "b-recommended__wrapper")
    # print(f"在 b-recommended__wrapper 中找到 {len(button_elements)} 个按钮。")
    getcardsnav() 
    for i in range(15):
        button_element = driver.find_element(By.XPATH, "/html/body/div/div[2]/main/div[1]/div[2]/div[1]/div/div[2]/button[1]")
        button_element.click()
        time.sleep(30)
        getcardsnav()
    

  
    


except TimeoutException:
    print("等待超时，未能找到指定的元素。")
finally:
    driver.quit()



unique_list = list({item['username']: item for item in listdata}.values())

listdata2 =[]
for i in unique_list:
    print(i['link'])
    # 初始化 WebDriver
    driver = webdriver.Chrome()
    userlist = []
    try:
        # 打开目标网页
        driver.get(i['link'])
        time.sleep(5)

        # 等待目标元素加载完成
        parent_element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '/html/body/div/div[2]/main/div[1]/div[1]/div/div[2]/div/div[2]/div[2]/div[2]'))
        )

        # 找到目标路径下的所有 <a> 标签
        a_tags = parent_element.find_elements(By.TAG_NAME, "a")

        # 遍历每个 <a> 标签
        for index, a_tag in enumerate(a_tags, start=1):
            # 获取 <a> 标签的 href 属性
            href = a_tag.get_attribute("href")

            # 获取 <a> 标签下的所有 <span> 元素
            span_elements = a_tag.find_elements(By.TAG_NAME, "span")

            # 提取所有 <span> 元素中的文字
            span_texts = [span.text for span in span_elements]

            # 打印结果
            # print(f"<a> 标签 {index}:")
            # print(f"  href: {href}")
            # print(f"  span 内容: {', '.join(span_texts) if span_texts else '无内容'}")
            
            print("-" * 40)
            str = "{}:{}".format(span_texts,href) 
            userlist.append(str)
            print(str)
            print("-" * 40)
        listdata2.append({'username': i['username'],'link':i['link'], 'contact': userlist})
    
    except Exception as e:
        print(f"发生错误: {e}")

    finally:
        # 关闭浏览器
        driver.quit()


csv_file = "user_data1.csv"
with open(csv_file, mode="w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=["username", "link", "contact"])
    writer.writeheader()  # 写入表头
    writer.writerows(listdata2)  # 写入数据
print(f"数据已写入 {csv_file}")